import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';
import type {
  Supplier,
  SupplierQueryParams,
  SupplierCreateParams,
  SupplierUpdateParams,
  SupplierStatusParams,
  SupplierPageResult
} from '@/types/base/BaseSupplier';

interface SupplierState {
  suppliers: Supplier[];
  paginatedSuppliers: Supplier[];
  currentSupplier: Supplier | null;
  total: number;
  currentPage: number;
  pageSize: number;
  loading: boolean;
  queryParams: SupplierQueryParams;
}

export const useBaseSupplierStore = defineStore('baseSupplier', {
  state: (): SupplierState => ({
    suppliers: [],
    paginatedSuppliers: [],
    currentSupplier: null,
    total: 0,
    currentPage: 1,
    pageSize: 10,
    loading: false,
    queryParams: {}
  }),

  actions: {
    setQueryParams(params: SupplierQueryParams) {
      this.queryParams = { ...params };
    },

    resetQueryParams() {
      this.queryParams = {};
      this.currentPage = 1;
      this.pageSize = 10;
    },

    setPagination(page: number, size: number) {
      this.currentPage = page;
      this.pageSize = size;
    },

    async getSuppliers(params: SupplierQueryParams = {}) {
      this.loading = true;
      try {
        const response = await request<SupplierPageResult>('/api/base/suppliers', {
          method: 'GET',
          params: { ...this.queryParams, ...params }
        });

        this.paginatedSuppliers = response.data.list;
        this.total = response.data.total;
        return response.data.list;
      } catch (error) {
        ElMessage.error('获取供应商列表失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async getSupplierDetail(id: number) {
      this.loading = true;
      try {
        const response = await request<Supplier>(`/api/base/suppliers/${id}`, {
          method: 'GET'
        });
        this.currentSupplier = response.data;
        return response.data;
      } catch (error) {
        ElMessage.error('获取供应商详情失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async createSupplier(data: SupplierCreateParams) {
      this.loading = true;
      try {
        await request('/api/base/suppliers', {
          method: 'POST',
          data
        });
        ElMessage.success('供应商创建成功');
        await this.getSuppliers();
      } catch (error) {
        ElMessage.error('供应商创建失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async updateSupplier(data: SupplierUpdateParams) {
      this.loading = true;
      try {
        await request(`/api/base/suppliers/${data.supplier_id}`, {
          method: 'PUT',
          data
        });
        ElMessage.success('供应商更新成功');
        await this.getSuppliers();
      } catch (error) {
        ElMessage.error('供应商更新失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async deleteSupplier(id: number) {
      this.loading = true;
      try {
        await request(`/api/base/suppliers/${id}`, {
          method: 'DELETE'
        });
        ElMessage.success('供应商删除成功');
        await this.getSuppliers();
      } catch (error) {
        ElMessage.error('供应商删除失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async toggleSupplierStatus(params: SupplierStatusParams) {
      this.loading = true;
      try {
        await request(`/api/base/suppliers/${params.supplier_id}/status`, {
          method: 'PATCH',
          data: { is_active: params.is_active }
        });
        ElMessage.success(`${params.is_active ? '启用' : '禁用'}供应商成功`);
        await this.getSuppliers();
      } catch (error) {
        ElMessage.error(`${params.is_active ? '启用' : '禁用'}供应商失败`);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    clearCurrentSupplier() {
      this.currentSupplier = null;
    }
  }
});
